package com.shuyun.xxx.guava.practice;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.concurrent.*;

/**
 * Created by goodb on 2017/5/18.
 */
public class CyclicBarrierTest implements Runnable{

    private CyclicBarrier cyclicBarrier = new CyclicBarrier(4, this);
    private Executor executor = Executors.newFixedThreadPool(4);
    private ConcurrentMap<String, Integer> count = Maps.newConcurrentMap();
    @Override
    public void run() {
        int result = 0;
        for(Map.Entry<String, Integer> entry : count.entrySet()){
            result += entry.getValue();
        }
        count.put(Thread.currentThread().getName(), result);
        System.out.println(count);
    }

    public void calculate(){
        for(int i = 1; i <= 4; i++){
            executor.execute(() -> {
                count.put(Thread.currentThread().getName(), 10);
                try{
                    System.out.println(Thread.currentThread().getName() + " is waiting");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName() + " is working");
                }catch (Exception e){

                }
            });
        }
    }

    public static void main(String[] args) {
        new CyclicBarrierTest().calculate();
    }
}
